import React, { PropTypes, Component } from 'react';
import Table from './MyTable'
import Column from './Column'
import {myAjax, getAuthShop, ROOTURL_TABLE, ROOTPATH} from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

export default React.createClass({
  getInitialState: function() {
    let date = new Date();
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      //有权限数据
      kllData: [{}],
      reserveData: [{}],
      serveData: [{}],
      //地区筛选后输入表格的数据
      tKllData: [{}],
      tReserveData: [{}],
      tServeData: [{}],

      areaArray: [],
      areaSelect: '请选择地区',
    };
  },
  componentWillMount: function() {
    let _this = this;
  },
  componentDidMount: function() {
    let _this = this;
    this.getData();
  },
  getData: function() {
    let _this = this;
    console.log('执行getData');
    myAjax(ROOTURL_TABLE + 'cafune/shop/shopmondailydata.api', 'POST', {year:this.state.year, month:this.state.month}, function(data) {
      this.setState({
        processData: data,
      }, () => {
        getAuthShop(null, function(data) {
          _this.setState({
            shopsForAdm: data,
          }, () => {
            // 处理数据格式为[{}]            
            let ids = _this.state.processData.shopIds;
            let processData = [];
            let areaArray = new Set(); 
            for(let i in ids) {
              let id = ids[i];
              processData.push(_this.state.processData[id]);
              areaArray.add(_this.state.processData[id].shopLoc);
            }           
            // 获取权限列表数组(有重复数据)
            let shopsForAdm = [];
            _this.state.shopsForAdm.forEach((shopMes) => {
              shopsForAdm.push(shopMes.dname);
            }); 
            // 过滤获取有权限数据
            let permissionData = processData.filter((data) => {
              if(shopsForAdm.indexOf(data['shopName']) === -1) {
                return false
              } else {
                return true 
              }
            });
            // 分离数据
            let kllCounts = [];
            for(let i in permissionData) {
              let a = {shopName: permissionData[i].shopName, shopLoc: permissionData[i].shopLoc};
              let b = permissionData[i].dailyKllCount;
              Object.assign(a, b);
              kllCounts.push(a);
            }
            let reserveCounts = [];
            for(let i in permissionData) {
              let a = {shopName: permissionData[i].shopName, shopLoc: permissionData[i].shopLoc};
              let b = permissionData[i].dailyReserveCount;
              Object.assign(a, b);
              reserveCounts.push(a);
            }
            let serveCounts = [];
            for(let i in permissionData) {
              let a = {shopName: permissionData[i].shopName, shopLoc: permissionData[i].shopLoc};
              let b = permissionData[i].dailyServeCount;
              Object.assign(a, b);
              serveCounts.push(a);
            }

            let filterKData = kllCounts.filter((data) => {
              if(shopsForAdm.indexOf(data['shopName']) === -1) {
                return false
              } else {
                areaArray.add(data.shopLoc);
                return true 
              }
            });
            let filterRData = reserveCounts.filter((data) => {
              if(shopsForAdm.indexOf(data['shopName']) === -1) {
                return false
              } else { return true }
            });
            let filterSData = serveCounts.filter((data) => {
              if(shopsForAdm.indexOf(data['shopName']) === -1) {
                return false
              } else { return true }
            });

            // 设置相应state，并回调执行地区筛选
            _this.setState({
              kllData: filterKData,
              reserveData: filterRData,
              serveData: filterSData,
              areaArray: Array.from(areaArray),
            }, () => {
              _this.filterData();
            });
          });
        }.bind(_this));
      });
    }.bind(_this), function(err) {});
  },
  changeArea: function(e) {
    let _this = this;
    let areaSelect = e.target.value;
    this.setState({
      areaSelect: areaSelect,
    }, () => {
      _this.filterData();
    });
  },
  filterData: function() {// 按地区筛选数据
    console.log('执行filterData');
    let _this = this;
    let areaSelect = this.state.areaSelect;
    if(areaSelect == '请选择地区') {
      this.setState({
        tKllData: _this.state.kllData,
        tReserveData: _this.state.reserveData,
        tServeData: _this.state.serveData,
      });
    } else {
      let tKllData = this.state.kllData.filter((data) => {
        return areaSelect == '请选择地区'||data.shopLoc == areaSelect
      });
      let tReserveData = this.state.reserveData.filter((data) => {
        return areaSelect == '请选择地区'||data.shopLoc == areaSelect
      });
      let tServeData = this.state.serveData.filter((data) => {
        return areaSelect == '请选择地区'||data.shopLoc == areaSelect
      });
      this.setState({
        tKllData: tKllData,
        tReserveData: tReserveData,
        tServeData: tServeData,
      });
    }    
  },
  handleClick: function() {
    let _this = this;

    let yearSelect = parseInt(this.state.year);
    let monthSelect = parseInt(this.state.month);
    if(!yearSelect || !(/^2\d{3}$/.test(yearSelect))) {
      alert("内容不能为空或格式错误");
      return
    }
    if(!monthSelect || !(/^0?[1-9]{1}$|1[0-2]/.test(monthSelect))) {
      alert("内容不能为空或格式错误");
      return
    }
    this.setState({
      year: yearSelect,
      month: monthSelect,
    }, _this.getData());
  },
  handleKeyPress: function(e) {
    if(e.which == 13) {
      this.handleClick();
    }
  },
  render: function() {
    return (
      <div>
        <div>
          <select value={this.state.areaSelect} onChange={this.changeArea}>
            <option value="请选择地区">请选择地区</option>
            {
              !this.state.areaArray[0]||this.state.areaArray.map((area) => {
                return (
                  <option value={area} key={area}>{area}</option>
                );
              })
            }
          </select>
          <label >
            <input onChange={(e)=>{this.setState({year: e.target.value})}} onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：2016" />年
            <span>&nbsp;&nbsp;</span><input onChange={(e)=>{this.setState({month: e.target.value})}} onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：3" />月
          </label>
          <button onClick={this.handleClick} className={styles.button}>确定</button>
        </div>
        <div>
          <Table data={this.state.tServeData} className={styles.container}>
            <Column dataKey='shopName' name='门店名称' width="120px" order="false" key={`col-shopName`}/>
            <Column dataKey='shopLoc' name='地区' width="60px" order="false" key={`col-shopLoc`}/>
            { 
              !this.state.tServeData[0]||Object.keys(this.state.tServeData[0]).map(entry => {
                if(/\d/g.test(entry)) {
                  return <Column dataKey={entry} name={entry} key={`col-${entry}`}/>
                }              
              })
            }
          </Table>
          <span className={styles.span}>当月客流量</span>
          <Table data={this.state.tKllData} className={styles.container}>
            <Column dataKey='shopName' name='门店名称' width="120px" order="false" key={`col-shopName`}/>
            <Column dataKey='shopLoc' name='地区' width="60px" order="false" key={`col-shopLoc`}/>
            { 
              !this.state.tKllData[0]||Object.keys(this.state.tKllData[0]).map(entry => {
                if(/\d/.test(entry)) {
                  return <Column dataKey={entry} name={entry} key={`col-${entry}`}/>
                }             
              })
            }
          </Table>
          <span className={styles.span}>当月预约量</span>
          <Table data={this.state.tReserveData} className={styles.container}>
            <Column dataKey='shopName' name='门店名称' width="120px" order="false" key={`col-shopName`}/>
            <Column dataKey='shopLoc' name='地区' width="60px" order="false" key={`col-shopLoc`}/>
            { 
              !this.state.tReserveData[0]||Object.keys(this.state.tReserveData[0]).map(entry => {
                if(/\d/.test(entry)) {
                  return <Column dataKey={entry} name={entry} key={`col-${entry}`}/>
                }              
              })
            }
          </Table>
        </div>
      </div>
    );
  }
});
